<script lang="tsx" setup>
import { computed, reactive, ref, watch } from 'vue';
import { type FormRules } from 'naive-ui';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import type { DictDataOption } from '@/typings/global';
import type { ClientVO } from '@/service/types/open';
import { addClient, editClient, getClient } from '@/service/api/open/client';
import FormLabelExtends from '@/components/custom/form-label-extends.vue';
import { generateClientKey, generateClientSecurity } from '@/utils/common';
import type { DictDataVo } from '@/service/types/developer';
import { addDictData, editDictData, getDictData } from '@/service/api/developer/dictData';
type Model = Pick<
  DictDataVo,
  'dictSort' | 'remark' | 'cssClass' | 'dictType' | 'listClass' | 'dictValue' | 'dictLabel' | 'dictCode'
>;
interface Props {
  operateType: NaiveUI.TableOperateType;
  currentId?: string | number | null | unknown;
  currentDict: DictDataVo;
}
const loading = ref(false);
interface Emits {
  (e: 'submitted'): void;
}
const show = ref<boolean>(false);
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
defineOptions({
  name: 'DictDataForm'
});
const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const rules: FormRules = {
  dictLabel: {
    required: true,
    message: '数据标签不能为空',
    trigger: 'blur'
  },
  dictValue: {
    required: true,
    message: '数据键值不能为空',
    trigger: 'blur'
  },
  listClass: {
    required: true,
    message: '请选择回显样式',
    trigger: 'blur'
  },
  dictSort: createRequiredRule('显示排序不能为空')
  // dictSort: {
  //   min: 0,
  //   max: 9999,
  //   message: '显示排序不能为空',
  //   trigger: 'blur'
  // }
};

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增字典数据',
    edit: '修改数据字典'
  };
  return titles[props.operateType];
});
const visible = defineModel<boolean>('visible', {
  default: false
});
const currentModelData = ref<ClientVO>();
const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
  return {
    dictCode: '',
    dictLabel: '',
    dictValue: '',
    listClass: null,
    dictType: '',
    cssClass: '',
    dictSort: 0,
    remark: ''
  };
}
const getDictDataByCode = async (id: number) => {
  show.value = true;
  const { error, data } = await getDictData(id);
  if (!error) {
    currentModelData.value = data?.data;
  }
  show.value = false;
};

async function handleInitModel() {
  Object.assign(model, createDefaultModel());
  if (props.operateType === 'edit' && props.currentId) {
    await getDictDataByCode(props.currentId as number);
    Object.assign(model, currentModelData.value);
  }
  model.dictType = props.currentDict?.dictType;
}
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

const closeModal = () => {
  visible.value = false;
};
const submitAddDictData = async (params: DictDataVo) => {
  const { error, data } = await addDictData(params);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
    closeModal();
    emit('submitted');
  }
};
const submitEditDictData = async (params: DictDataVo) => {
  const { error, data } = await editDictData(params);
  loading.value = false;
  if (!error) {
    (window as any).$message?.success(data?.msg);
    closeModal();
    emit('submitted');
  }
};
async function handleSubmit() {
  await validate();
  loading.value = true;
  const { ...params } = model;
  if (!props.currentId) {
    await submitAddDictData(params as DictDataVo);
  } else {
    await submitEditDictData({ ...params, dictCode: props.currentId } as DictDataVo);
  }
}
const listClassOption = ref([
  {
    label: '默认(Default)',
    value: 'default'
  },
  {
    label: '主要(Primary)',
    value: 'primary'
  },
  {
    label: '成功(Success)',
    value: 'success'
  },
  {
    label: '信息(Info)',
    value: 'info'
  },
  {
    label: '警告(Warning)',
    value: 'warning'
  },
  {
    label: '危险(Error)',
    value: 'error'
  }
]);
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-740px">
    <NSpin :show="show">
      <NForm ref="formRef" :model="model" :rules="rules">
        <NGrid x-gap="12" responsive="screen" item-responsive>
          <NFormItemGi span="24 s:12 m:12" label="数据标签" path="dictLabel">
            <NInput v-model:value="model.dictLabel" placeholder="请输入数据标签" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="数据键值" path="dictValue">
            <NInput v-model:value="model.dictValue" placeholder="请输入数据键值" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="样式属性" path="cssClass">
            <NInput v-model:value="model.cssClass" placeholder="请输入样式属性" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="回显样式" path="listClass">
            <NSelect v-model:value="model.listClass" filterable placeholder="选择回显样式" :options="listClassOption" />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" path="dictSort" label="显示排序">
            <NInputNumber
              v-model:value="model.dictSort"
              :min="0"
              :max="9999"
              class="w-100%"
              clearable
              placeholder="请输入显示排序"
            />
          </NFormItemGi>
          <NFormItemGi span="24 s:12 m:12" label="备注" path="remark">
            <NInput v-model:value="model.remark" type="textarea" placeholder="请输入备注" />
          </NFormItemGi>
        </NGrid>
      </NForm>
    </NSpin>

    <template #footer>
      <NSpace justify="end">
        <NButton @click="closeModal">取消</NButton>
        <NButton type="primary" :loading="loading" @click="handleSubmit">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss" scoped></style>
